import DNS
import MySQLdb
import sys
import requests
import re
import time
import os

def FindIp(url):
	query = sys.argv[0]
	DNS.DiscoverNameServers()
	reqobj = DNS.Request(url)
	answerobj = reqobj.req(name = query, qtype = DNS.Type.A)
	if not len(answerobj.answers):
		return 
	for item in answerobj.answers:
		ip = ("%s") % (item['data']) 
	return ip
	
def FindAdre(ip):
	if ip:
		try:
			adre_url= "http://www.ip138.com/ips138.asp?ip="+ip+"&action=2"
			adre_get= requests.get(adre_url)
			adre_get.raise_for_status()
			adre_get.encoding = "gb2312"
			keyword = re.compile(r'''<td align="center"><ul class="ul1"><li>(.*?)</li><li>''', re.U|re.S)
			unic = keyword.findall(adre_get.text)
			str = ''.join(unic)
			return str
		except:
			print "error"
	else :
		return  0

def MySQLSave(url, ip, adre):
	db = MySQLdb.connect("172.26.253.3","root","platform","WangJunX",charset = "utf8")
	cursor = db.cursor()
	cursor.execute('INSERT INTO UIA (url, ip, adress) values ( %s, %s, %s)', [url, ip, adre])
	db.commit()
	return 

def main():
	start = time.time()
	a = open("URL.txt",'r')
	'''fo_0 = open("adre.txt",'w')'''
	fo_1 = open("ip.txt",'w') 
	num = 0
	while 1:
		if  num <=992:
			url = a.readline()[:-1]
			num = num +1
			ip = FindIp(url)
			if ip:
				adre = FindAdre(ip)
				fo_1.write(ip+'\n')	
				print "%-4d %-30s %-40s %-30s" % (num, url, ip, adre)
				MySQLSave(url, ip, adre)
			else:
				fo_1.write("NULL"+'\n')
				print "%-4d %-30s %-40s"  %  (num, url, "NotFound")
		else:
			break
	a.close()
	'''fo_0.close()'''
	fo_1.close()
	end = time.time()
	print "TIME:  ",end - start, "S"
if __name__=='__main__':
	main()